﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dashboard.Models;

namespace Dashboard.Services
{
    public class StatDataRepository : IStatDataRepository
    {
        private const string CacheKey = "ContactStore";

        public StatDataRepository()
        {
            var ctx = HttpContext.Current;

            if (ctx != null)
            {
                if (ctx.Cache[CacheKey] == null)
                {
                    var statData = new StatData[]
                    {
                        new StatData(0)
                    };
                    ctx.Cache[CacheKey] = statData;
                }
            }
        }

        public int GetID()
        {
            var ctx = HttpContext.Current;

            if (ctx != null)
            {
                var currentData = ((StatData[])ctx.Cache[CacheKey]).ToList();
                StatData newDevice = new StatData(currentData.Count - 1);
                currentData.Add(newDevice);
                ctx.Cache[CacheKey] = currentData.ToArray();
                return newDevice.ID;
            }

            return 0;
        }
        public bool AddData(int ID, byte CPU, byte HDD, byte RAM)
        {
            var ctx = HttpContext.Current;

            if (ctx != null)
            {
                try
                {
                    var currentData = ((StatData[])ctx.Cache[CacheKey]).ToList();
                    currentData[ID].CPU.Add(CPU);
                    currentData[ID].HDD.Add(HDD);
                    currentData[ID].RAM.Add(RAM);
                    ctx.Cache[CacheKey] = currentData.ToArray();
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return false;
                }
            }

            return false;
        }
        public StatData GetData(int id)
        {
            var ctx = HttpContext.Current;

            if (ctx != null)
            {
                try
                {
                    return ((StatData[])ctx.Cache[CacheKey])[id];
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            return null;
        }
    }
}
